Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

383
Visualizações
How to Convert File Image to Byte[] ReactJS?

I want to send image to api end point and end point accept byte[] how can i handle this. My code is: ReactJS function on upload button click:

    let onClickHandler = () => {
        let data = new FormData()
        data.append('file', image);

        axios.post("/Contact/ContactForm/",  {
            
            AttachedImage: data

        }, {
            
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'X-Requested-With': 'XMLHttpRequest',
                }
            // receive two parameter endpoint url ,form data
        })
            .then(res => { // then print response status
                console.log('binary Response......',res.statusText)
            });
}

and my endpoint controller method:

[HttpPost]
        public async Task<IActionResult> ContactForm([FromBody] Contact model)
        {
            try
            {
                model.CreationDate = DateTime.Now;
                await _contact.ContactForm(model);
                return Ok("Submitted Successfully");
            }
            catch (Exception ex) { return this.BadRequest("Not Submitted Successfully" + ex.ToString()); }
        }

and finally Model.cs Class

public byte[] AttachedImage { set; get; }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

want to send image to api end point and end point accept byte[] how can i handle this.

Please note that the default model binder can not handle byte array that would be set to null.

To upload image file and bind the data to a byte array property of your model class, you can try following solutions:

Solution 1 - convert the selected image file to base64 encoded string, and use a ByteArrayModelBinder to convert it into a byte array.

public class Contact
{
    [ModelBinder(BinderType = typeof(ByteArrayModelBinder))]
    public byte[] AttachedImage { set; get; }
    public DateTime CreationDate { set; get; }

    //...
    //other properties
    //...
 }

Testing Data

{
    "attachedImage": "iVBORw0KGgoAAAANSUhEUgAAAMsAAA.....",
    "creationDate": "2021-08-21T15:12:05"
}

Testing Result

enter image description here

Solution 2 - implement and use a custom model binder like below to bind selected image file to byte array.

public class ImageToByteArrayModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        // ...
        // implement it based on your actual requirement
        // code logic here
        // ...



        if (bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"]?.Length > 0)
        {
            var fileBytes = new byte[bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].Length];

            using (var ms = new MemoryStream())
            {
                bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].CopyTo(ms);
                fileBytes = ms.ToArray();
            }

            bindingContext.Result = ModelBindingResult.Success(fileBytes);
        }



        return Task.CompletedTask;
    }
}

Testing Result

enter image description here

about 4 years ago · Juan Pablo Isaza Relatório

0

It's hard to know if the API will accept it, but you can convert the file to a Uint8Array which is an array with all bytes of the file represented as Integers.

let file: File = ...
let uint8 = new Uint8Array(await file.arrayBuffer())
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda